import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart'
    as webview_flutter_android;

import 'app_theme.dart';

class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key, required this.title, required this.url});

  final String title;
  final String url;

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

double linearProgress = 0.0;
bool isLightMode = true;
late WebViewController _controller;

Future<bool> _exitApp(BuildContext context) async {
  if (await _controller.canGoBack()) {
    print("onwill goback");
    _controller.goBack();
    return Future.value(false);
  } else {
    debugPrint("_exit will not go back");
    return Future.value(true);
  }
}

class _WebViewPageState extends State<WebViewPage> {
  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    _controller = WebViewController.fromPlatformCreationParams(
        const PlatformWebViewControllerCreationParams());
    _controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(
          isLightMode ? AppTheme.nearlyWhite : AppTheme.nearlyBlack)
      ..setNavigationDelegate(NavigationDelegate(
        onProgress: (int progress) {
          linearProgress = progress / 100.0;
        },
      ))
      ..loadRequest(Uri.parse(widget.url));
    addFilesController(_controller);
  }

  Future<void> addFilesController(WebViewController controllerV) async {
    if (Platform.isAndroid) {
      var controller = (controllerV.platform
          as webview_flutter_android.AndroidWebViewController);
      await controller.setOnShowFileSelector(_androidFilePicker);
    }
  }

  Future<List<String>> _androidFilePicker(
    webview_flutter_android.FileSelectorParams params,
  ) async {
    if (params.acceptTypes.any((type) => type == 'image/*')) {
      // 弹出对话框让用户选择相机或相册
      final pickedSource = await _showImageSourceDialog(context);

      if (pickedSource == null) {
        return [];
      }

      // 调用图片选择或拍照方法
      final XFile? image = await _picker.pickImage(source: pickedSource);

      if (image == null) {
        return [];
      }
      print(File(image.path).uri.toString());
      // 获取图片的路径
      return [File(image.path).uri.toString()];

      //压缩图片
      // var imageData = await image.readAsBytes();
      // var decodedImage = image.decodeImage(imageData)!;
      // var scaledImage = image.copyResize(decodedImage, width: 500);
      // var jpg = image.encodeJpg(scaledImage, quality: 90);
      //
      // var filePath = (await getTemporaryDirectory()).uri.resolve(
      //   './image_${DateTime.now().microsecondsSinceEpoch}.jpg',
      // );
      // var file = await File.fromUri(filePath).create(recursive: true);
      // await file.writeAsBytes(jpg, flush: true);
      //
      // return [file.uri.toString()];
    }

    return [];
  }

  Future<ImageSource?> _showImageSourceDialog(BuildContext context) {
    return showDialog<ImageSource>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('选择图片来源'),
          content: SizedBox(
            height: 120, // 控制弹窗的高度
            child: GridView.count(
              crossAxisCount: 2, // 设置为2列
              crossAxisSpacing: 10, // 列间距
              mainAxisSpacing: 10, // 行间距
              children: [
                GestureDetector(
                  onTap: () => Navigator.pop(context, ImageSource.camera),
                  child: const Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.camera_alt, size: 40), // 拍照图标
                      Text('拍照', style: TextStyle(fontSize: 16)),
                    ],
                  ),
                ),
                GestureDetector(
                  onTap: () => Navigator.pop(context, ImageSource.gallery),
                  child: const Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.photo_library, size: 40), // 相册图标
                      Text('相册', style: TextStyle(fontSize: 16)),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }


  @override
  Widget build(BuildContext context) {
    var brightness = MediaQuery.of(context).platformBrightness;
    isLightMode = brightness == Brightness.light;
    return WillPopScope(
      onWillPop: () => _exitApp(context),
      child: Scaffold(
          body: Padding(
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        child: Stack(children: [
          LinearProgressIndicator(
            backgroundColor: AppTheme.grey,
            color: AppTheme.accentColor,
            minHeight: 1,
            valueColor:
                const AlwaysStoppedAnimation<Color>(AppTheme.accentColor),
            value: linearProgress,
          ),
          WebViewWidget(controller: _controller)
        ]),
      )),
    );
  }
}
